<?php

/**
 * 会员等级
 */

namespace app\admin\controller;

use think\Lang;
use app\common\model\MemberGroup as MemberGroupModel;
use think\Request;
use think\Db;

class Membergrade extends AdminControl {

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/Membergrade.lang.php');
    }

    public function index() {
        if (request()->isPost()) {
            $update_arr = array();
            if (!empty(input('post.mg/a'))) {
                $mg_arr = array();
                $i = 1;
                $max_exppoints = '-1';#用户判断 下级会员等级积分应大于上级等级积分
                foreach (input('post.mg/a') as $k => $v) {
                    $mg_arr[$i]['level'] = $i;
                    $level_name = $v['level_name'];
                    $exppoints  = intval($v['exppoints']);
                    if(empty($level_name)){
                        $this->error(lang('param_error'));
                    }
                    $mg_arr[$i]['level_name'] = $level_name;
                    //所需经验值
                    if($max_exppoints>=$exppoints){
                        $this->error($level_name.'经验值应大于'.$max_exppoints);
                    }else{
                        $mg_arr[$i]['exppoints'] = $exppoints;
                    }
                    $max_exppoints = $exppoints;
                    $i++;
                }
                $update_arr['member_grade'] = serialize($mg_arr);
            } else {
                $this->error('必须设置会员等级');
            }
            $result = true;
            if ($update_arr) {
                $config_model = model('config');
                $result = $config_model->editConfig($update_arr);
            }
            if ($result) {
                $this->log(lang('sc_edit') . lang('sc_member_grade'), 1);
                $this->success(lang('sc_common_save_succ'));
            } else {
                $this->log(lang('sc_edit') . lang('sc_member_grade'), 0);
                $this->error(lang('sc_common_save_fail'));
            }
        } else {
            $list_config = rkcache('config', true);
            $membergrade_list = $list_config['member_grade'] ? unserialize($list_config['member_grade']) : array();
            $this->assign('membergrade_list', $membergrade_list);
            $this->setAdminCurItem('index');
            return $this->fetch();
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            // array(
            //     'name' => 'index',
            //     'text' => '管理',
            //     'url' => url('Membergrade/index')
            // ),
            array(
                'name' => 'member_group',
                'text' => '会员组设置',
                'url' => url('Membergrade/member_group')
            )
        );
        return $menu_array;
    }

    /**
     * 初始化会员组
     * @link /admin/Membergrade/setDefaultGroup
     */
    public function setDefaultGroup()
    {
        $insert = [
            [
                'group_name' => '批发商',
                'group_config' => json_encode([
                    'member_group'      => MEMBER_AGENT_GROUP, // 会员组
                    'commission_rate_1' => '0.2',              // 佣金比例
                    'price_1'           => '0.8',              // 价格比例
                    'commission_rate_2' => '0.1',              // 佣金比例
                    'price_2'           => '0.9',              // 价格比例
                    'read_bonded_goods' => 1                   // 1可以查看保税货物信息 2不可以
                ]),
            ],
            [
                'group_name' => '普通会员',
                'group_config' => json_encode([
                    'member_group'      => MEMBER_CUSTOMER_GROUP, // 会员组
                    'commission_rate_1' => '0',                   // 佣金比例
                    'price_1'           => '0.9',                 // 价格比例
                    'commission_rate_2' => '0',                   // 佣金比例
                    'price_2'           => '1',                   // 价格比例
                    'read_bonded_goods' => 2                      // 1可以查看保税货物信息 2不可以
                ]),
            ],
        ];

        Db::startTrans();
        try {
            Db::execute('TRUNCATE `sc_member_group`'); // 清空截断表
            Db::name('member_group')->insertAll($insert);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['msg' => '初始化失败', 'err_msg' => $e->getMessage()]);
        }

        return json(['code' =>10000, 'message' => '初始化成功']);
    }

    /**
     * 会员组设置
     */
    public function member_group()
    {
        $membergrade_list = MemberGroupModel::all();
        $this->assign('membergrade_list', $membergrade_list);
        $this->setAdminCurItem('member_group'); // 当前选中的标签
        return $this->fetch();
    }

    /**
     * 会员组保存
     */
    public function memberGroupSave()
    {
        $post = $this->request->post();

        # 将参数序列化保存
        if (!isset($post['id']) || empty($post['id'])) {
            return $this->error('缺少参数');
        }

        $ids               = $post['id'];                // 初始化时 $ids[0]=>批发商 1普通会员
        $member_group      = $post['member_group'];      // 1=>批发商 9=>普通会员
        $commission_rate_1 = $post['commission_rate_1']; // 一级佣金比例
        $commission_rate_2 = $post['commission_rate_2']; // 二级
        $price_1           = $post['price_1'];           // 一级价格比例
        $price_2           = $post['price_2'];           // 二级
        $read_bonded_goods = $post['read_bonded_goods']; // 批发商可以查看保税货物信息

        $update = [];
        foreach ($ids as $k => $id) {
            $config = [
                'member_group'      => $member_group[$k],
                'commission_rate_1' => $commission_rate_1[$k],
                'commission_rate_2' => $commission_rate_2[$k],
                'price_1'           => $price_1[$k],
                'price_2'           => $price_2[$k],
                'read_bonded_goods' => $read_bonded_goods[$k],
            ];
            $update[] = [
                'id' => $id,
                'group_config' => json_encode($config),
            ];
        }

        $member_group_model = new MemberGroupModel();
        $result = $member_group_model->saveAll($update);
        if ($result) {
            # 更新缓存
            $data = $member_group_model->getMemberGroupConfig();
            wkcache('member_group', $data);
            return $this->success('保存成功');
        }
        return $this->error('保存失败');
    }

    /**
     * @link /admin/Membergrade/test_cs
     *       http://shopcloudwj.ykzx/admin/Membergrade/test_cs
     */
    public function test_cs()
    {
        $data = rkcache('member_group', true);
        echo 'test_cs';
        halt($data);
    }
}
